<template>
  <div>
    <el-checkbox-group v-model="roleId">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="Save">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getUserDetailById } from '@/api/user'
import { getRoles, assignRoles } from '@/api/employees'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      roleId: [], // 用户的角色
      list: [] // 选中项的id
    }
  },
  watch: {
    curId(newVal, oldVal) {
      console.log('子组件内，发现了curId的变化：新值：', newVal, '的旧值', oldVal)
      // 取出当前用户已经有的角色
      this.loadUserRoles()
    }
  },
  created() {
    this.loadRoles()
    this.loadUserRoles()
  },
  methods: {
    // 点击确定按钮保存
    async  Save() {
      const res = await assignRoles({ id: this.curId, roleIds: this.roleId })
      console.log('保存当前角色详情 ', res)
      this.$message.success('操作成功')
      // 关闭弹层
      this.closeDialog()
    },
    // 关闭
    closeDialog() {
      this.$emit('close-dialog')
      this.roleId = []
    },
    // 获取分配角色
    async loadRoles() {
      const res = await getRoles({ page: 1, pagesize: 200 })
      console.log('获取分配角色', res)
      this.list = res.data.rows
    },
    // 获取当前用户的角色
    async loadUserRoles() {
      const res = await getUserDetailById(this.curId)
      console.log('获取当前用户的角色信息', res)
      this.roleId = res.data.roleIds
    }
  }
}
</script>
